<?php
declare(strict_types=1);
namespace Service\UserService;

use Service\Code\Normal;
use App\Model\BbcModel\CashManager;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\Cashcheck;
use Service\BaseService;
use App\Model\BbcModel\CashRegister;
use Service\ConfigureService\ChannelConfigService;
use Hyperf\DbConnection\Db;
use Service\AreaService\AreaService;
use Service\ChannelService\StoreConfigService;
use App\Model\BbcModel\VipConfig;
use App\Model\BbcModel\GoodsPointsConfig;

/**
 * 收银用户登录
 * @author chenshubo
 */

class CashManagerService extends BaseService
{
    /**
     * user login encrypt iv
     * @access private
     * @var    string
     */
    const USER_LOGIN_ENCRYPTIV = 'usersAutoLoginIv';
    
    /**
     * user login token salt
     * @access private
     * @var    string
     */
    const USER_TOKEN_SALT = 'userTokenSalt';
    
    /**
     * 获取收银员信息
     * @param int $manager_id
     */
    public function getCashUserInfo( int $manager_id )
    {
        return CashManager::instance()->info(['id' => $manager_id]);
    }
    

    /**
     * 获取收银员信息
     * @param array $ids
     */
    public function getCasherByIds( array $ids = [] )
    {
        return CashManager::instance()->whereIn('id',$ids)->get()->toArray();
    }
    
    /**
     * 获取收银机信息
     * @param array $ids
     */
    public function getCashRegisterByIds( array $ids = [] )
    {
        return CashRegister::instance()->whereIn('id',$ids)->get()->toArray();
    }
    
    /**
     * 登录
     * @param array $param
     */
    public function userLogin( array $param = [])
    {
        if (empty($param['account'])) {
            return Normal::returnCode(Normal::FAIL, '账号不能为空');
        }
        
        if (empty($param['password'])) {
            return Normal::returnCode(Normal::FAIL, '密码不能为空');
        }
        
        if (empty($param['mac'])) {
            return Normal::returnCode(Normal::FAIL,'登录设备mac地址不能为空，请联系相关业务人员进行处理');
        }
        
        //验证账号信息
        $manager = CashManager::instance()->info(['account' => $param['account']]);
        if (empty($manager)) {
            return Normal::returnCode(Normal::FAIL, '账号不存在');
        }
        
        if ($manager['status'] != 1) {
            return Normal::returnCode(Normal::FAIL, '账号被冻结');
        }
        
        if ($manager['password'] != md5($param['password']) && $manager['password'] != $param['password']) {
            return Normal::returnCode(Normal::FAIL, '密码错误');
        }
        
        $cashregister= CashRegister::instance()->info(['df'=>0,'mac'=>$param['mac'],'mn_sid'=>$manager['mn_sid']]);
        if(empty($cashregister)){
            return Normal::returnCode(Normal::FAIL, '收银台不存在');
        }
        
        if($cashregister['status']!=1){
            return Normal::returnCode(Normal::FAIL, '收银台被禁用');
        }
        
        $mnuser= Mnuser::instance()->info(['id'=>$cashregister['mn_sid']]);
        if(empty($mnuser)){
            return Normal::returnCode(Normal::FAIL, '未找到店铺');
        }
        if($mnuser['status']==0){
            return Normal::returnCode(Normal::FAIL, '该店铺已被禁用');
        }
        if($mnuser['type']==1){
            return Normal::returnCode(Normal::FAIL, '未开实体店铺');
        }
        
        $encrypt_str = json_encode([
            'manager_id'    => $manager['id'],
            'sid'           => $manager['sid'],
            'cid'           => $manager['cid'],
            'mn_sid'        => $manager['mn_sid'],
            'casher_id'     => $cashregister['id'],
            'timestamp'     => time()
        ]);
        $token = $this->keyEncrypt($encrypt_str);
        $cashcheckwhere=[
            ['df', '=', 0],
            ['mn_sid', '=', $mnuser['id']],
            ['cid', '=', $mnuser['pid']],
            ['casher_id','=',$cashregister['id']],
            '_order_'=>['id'=>'desc']
        ];
        $first_time=0;
        $cascheck= Cashcheck::instance()->info($cashcheckwhere);
        if($cascheck){
            $first_time = $cascheck['last_time'];
        }
        
        $price = 199;
//        $config= ChannelConfigService::instance()->getConfig(['cid'=>$manager['cid'],'code'=>'member_vip_fee']);
//        if(isset($config['data']['value']['year'])){
//            $price=$config['data']['value']['year'];
//        }
        $config= VipConfig::instance()->info(['cid'=>$manager['cid'],'type'=>1]);
        if(isset($config['year'])){
            $price=$config['year'];
        }
        
        $is_support_face=0;
        $faceconfig= ChannelConfigService::instance()->getConfig(['cid'=>$manager['cid'],'code'=>'faceplus_config']);
        if(isset($faceconfig['data']['value']['is_support'])){
            $is_support_face=$faceconfig['data']['value']['is_support'];
        }
        $areas= AreaService::instance()->queryAreaListById([$mnuser['province'],$mnuser['city'],$mnuser['area']]);
        
        $order_money_limit='';
        $cashregister_limit_config = StoreConfigService::instance()->getConfig('cashregister_limit',$manager['mn_sid']);
        if(isset($cashregister_limit_config['order_money_limit'])){
            $order_money_limit=$cashregister_limit_config['order_money_limit'];
        }
        $cash_login_config = StoreConfigService::instance()->getConfig('cash_login_config',$manager['mn_sid']);
        $goodsPointsConfig= GoodsPointsConfig::instance()->info(['cid'=>$manager['cid']]);

        $data=[
            'token'                   => $token,
            'store_name'              => $mnuser['store_name'],
            'store_address'           => $mnuser['store_address'],
            'link_mobile'             => $mnuser['link_mobile'],
            'name'                    => $manager['name'],
            'pay_way'                 => \explode(',', $mnuser['pay_way']),
            'stock_share'             => $mnuser['stock_share'],
            'manager_id'              => $manager['id'],
            'mn_sid'                  => $manager['mn_sid'],
            'printgoodsdetail'        => $mnuser['printgoodsdetail'],
            'last_time'               => $first_time,
            'vip_price'               => $price,
            'type'                    => (int)$mnuser['type'],
            'cashier_logo'            => $mnuser['cashier_logo'],
            'cashier_customer_code'   => $mnuser['cashier_customer_code'],
            'province'                => $mnuser['province'] ? $areas[$mnuser['province']] : '',
            'city'                    => $mnuser['city'] ? $areas[$mnuser['city']] : '',
            'area'                    => $mnuser['area'] ? $areas[$mnuser['area']] : '',
            'address'                 => $mnuser['address'] ?? '',
            'order_money_limit'       => $order_money_limit,
            'cashregister_name'       => $cashregister['name'],
            'cash_logo_img'           => $cash_login_config['cash_logo_img'] ?? '',
            'cash_agreement'          => $cash_login_config['cash_agreement'] ?? '',
            'cash_modify_price'       => $mnuser['cash_modify_price'],
            'is_support_face'         => $is_support_face,
            'points_use_store_status' => $goodsPointsConfig['points_use_store_status'] ?? 0,
        ];
        $data['cash_guide_show'] = $cash_login_config['cash_guide_show'] ?? 0;
        $data['cash_ware_show'] = $cash_login_config['cash_ware_show'] ?? 0;
        if($mnuser['type']==3) {
            $data['pay_way']= [3];
        }
        CashManager::instance()->edit(['id'=>$manager['id']], ['token'=>$token]);
        Cashregister::instance()->edit(['id'=>$cashregister['id']], ['online'=>1,'time'=>time()]);
        return Normal::returnCode(Normal::SUC, '登录成功', $data);
    }
    
    /**
     * 加密key
     * @param  string $encrypt_str
     * @access private
     * @return string
     */
    public function keyEncrypt(string $encrypt_str)
    {
        return openssl_encrypt($encrypt_str, 'AES-256-CBC',self::USER_TOKEN_SALT, 0, self::USER_LOGIN_ENCRYPTIV);
    }
    
    /**
     * 解密key
     * @param  string $decrypt_str
     * @access private
     * @return string
     */
    public function keyDecrypt(string $decrypt_str)
    {
        return openssl_decrypt($decrypt_str, 'AES-256-CBC', self::USER_TOKEN_SALT, 0, self::USER_LOGIN_ENCRYPTIV);
    }

    /**
     * 获取收银员列表
     * @param int $mn_sid
     */
    public function getCashUsers(int $cid,int $mn_sid)
    {
        $cashManagerTable = CashManager::instance()->getTable();
        //收银账目表的最大日期子查询
        $cashCheckSubQuery = Cashcheck::instance()->select([
            'cid', 'mn_sid', 'casher_id', 'last_time'
        ])->where('mn_sid', $mn_sid)->whereIn('id', function ($query) use ($mn_sid) {
            $query->from(Cashcheck::instance()->getTable())->select([
                Db::raw("max(id) id")
            ])->where('mn_sid', $mn_sid)->groupBy('cid', 'mn_sid', 'casher_id');
        });
        
        //查询收银员数据
        $managers = CashManager::instance()
        ->from($cashManagerTable . ' as cm')
        ->LeftjoinSub($cashCheckSubQuery, 'cc', function ($join) {
            $join->on('cc.cid', '=', 'cm.cid')
            ->on('cc.mn_sid', '=', 'cm.mn_sid')
            ->on('cc.casher_id', '=', 'cm.id');
        })
        ->select([
            'cm.*',
            Db::raw('IFNULL(cc.last_time,0) AS last_time')
        ]
        )
        ->where('cm.mn_sid', $mn_sid)
        ->get()->toArray();
        return Normal::returnCode(Normal::SUC, '成功', $managers);        
    }
    
    
    /**
     * 修改收银员密码
     * @param int $mn_sid
     */
    public function editPassword(int $manager_id,array $body = [] )
    {
        if (empty($body['oldpassword'])) {
            return Normal::returnCode(Normal::FAIL, '原始密码不能为空');
        }
        
        if (empty($body['newpassword'])) {
            return Normal::returnCode(Normal::FAIL, '新密码不能为空');
        }
        
        
        $oldpassword = $body['oldpassword'];
        $newpassword = $body['newpassword'];
        
        if( $oldpassword == $newpassword ) {
            return Normal::returnCode(Normal::FAIL, '新旧密码一致');
        }
        
        $manager= $this->getCashUserInfo((int)$manager_id);
        if( md5($oldpassword) != $manager['password'] ) {
            return Normal::returnCode(Normal::FAIL, '旧密码错误');
        }
        
        $result= CashManager::instance()->where('id',$manager_id)->update([
            'password'  => md5($newpassword),
            'md'        => time()
        ]);
        
        if( $result) {
            return Normal::returnCode(Normal::SUC, '修改成功');
        }
        return Normal::returnCode(Normal::FAIL, '修改失败');
    }
    
    /**
     * 修改昵称
     * @param string $manager_id
     * @param string $name
     * @return type
     */
    public function editName(int $manager_id,array $body = [])
    {
        if (empty($body['name'])) {
            return Normal::returnCode(Normal::FAIL, '昵称不能为空');
        }
        $manager= $this->getCashUserInfo((int)$manager_id);
        if( $body['name'] == $manager['name'] ) {
            return Normal::returnCode(Normal::FAIL, '新旧昵称一致');
        }
        $result= CashManager::instance()->where('id',$manager_id)->update([
            'name'      => $body['name'],
            'md'        => time()
        ]);
        
        if( $result) {
            return Normal::returnCode(Normal::SUC, '修改成功');
        }
        return Normal::returnCode(Normal::FAIL, '修改失败');
    }
    
    /**
     * 验证收银员改价密码
     * @param int $mn_sid
     * @param array $body
     * @return type
     */
    public function checkCashModifyPricePasswd(int $mn_sid,array $body=[]) {
        if (empty($body['cash_modify_passwd'])) {
            return Normal::returnCode(Normal::FAIL, '收银改价密码，必传');
        }
        $mnuser= Mnuser::instance()->info(['id'=>$mn_sid]);
        if(empty($mnuser)){
            return Normal::returnCode(Normal::FAIL, '未找到相关店铺');
        }
        if($mnuser['cash_modify_price']==0){
            return Normal::returnCode(Normal::FAIL, '该店铺未启用收银员改价');
        }
        if($mnuser['cash_modify_passwd']!= md5($body['cash_modify_passwd'])){
            return Normal::returnCode(Normal::FAIL, '密码错误');
        }
        return Normal::returnCode(Normal::SUC, '密码验证成功');
    }
    
    /**
     * pda登录
     * @param array $param
     * @return type
     */
    public function pdaLogin(array $param = []) {
        if (empty($param['account'])) {
            return Normal::returnCode(Normal::FAIL, '账号不能为空');
        }
        
        if (empty($param['password'])) {
            return Normal::returnCode(Normal::FAIL, '密码不能为空');
        }
        //验证账号信息
        $manager = CashManager::instance()->info(['account' => $param['account']]);
        if (empty($manager)) {
            return Normal::returnCode(Normal::FAIL, '账号不存在');
        }
        
        if ($manager['status'] != 1) {
            return Normal::returnCode(Normal::FAIL, '账号被冻结');
        }
        
        if ($manager['password'] != md5($param['password']) && $manager['password'] != $param['password']) {
            return Normal::returnCode(Normal::FAIL, '密码错误');
        }
        $mnuser= Mnuser::instance()->info(['id'=>$manager['mn_sid']]);
        if(empty($mnuser)){
            return Normal::returnCode(Normal::FAIL, '未找到店铺');
        }
        if($mnuser['status']==0){
            return Normal::returnCode(Normal::FAIL, '该店铺已被禁用');
        }
        if($mnuser['type']==1){
            return Normal::returnCode(Normal::FAIL, '未开实体店铺');
        }
        $encrypt_str = json_encode([
            'manager_id'    => $manager['id'],
            'sid'           => $manager['sid'],
            'cid'           => $manager['cid'],
            'mn_sid'        => $manager['mn_sid'],
            'timestamp'     => time()
        ]);
        $token = $this->keyEncrypt($encrypt_str);
        $data=[
            'token'=>$token,
            'account'=>$manager['account'],
            'name'=>$manager['name']
        ];
        CashManager::instance()->edit(['id'=>$manager['id']], ['pdatoken'=>$token]);
        return Normal::returnCode(Normal::SUC, '登录成功', $data);
    }
    
    public function getInfo(int $manager_id) {
        $info =CashManager::instance()->info(['id' => $manager_id]);
        $data =[
            'account'=>$info['account'],
            'name'=>$info['name']
        ];
        return Normal::returnCode(Normal::SUC, '登录成功', $data);
    }
}
